package com.biglead.mini.controller;

import com.biglead.common.pojo.CommonResult;
import com.biglead.common.pojo.MiniLoginCodeRequest;
import com.biglead.common.pojo.MiniLoginRequest;
import com.biglead.common.pojo.UserInfo;
import com.biglead.feign.clients.FeignAuthClient;
import com.biglead.feign.clients.FeignUserClient;
import com.biglead.feign.clients.FeignWxClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wx")
public class LoginController {

    @Resource
    private FeignWxClient feignWxClient;
    @Resource
    private FeignUserClient feignUserClient;
    @Resource
    private FeignAuthClient feignAuthClient;
    @Value("${server.port}")
    private String serverPort;

    /**
     * @return 用户
     */
    @PostMapping(value = "/login_by_weixin")
    public CommonResult queryById(@RequestBody MiniLoginRequest request, @RequestHeader String appId) {
        log.info("微信登录 port {}", serverPort);
        request.setAppId(appId);
        Map<String, Object> map = feignWxClient.miniLogin(request);
        if (map.containsKey("code") && Integer.parseInt(map.get("code").toString()) == 200) {
            log.info("微信登录成功 port {}", map);
            String openId = map.get("openId").toString();
            String sessionKey = map.get("sessionKey").toString();
            String nickName = map.get("nickName").toString();
            String avatarUrl = map.get("avatarUrl").toString();

            UserInfo userInfo = feignUserClient.queryByOpenId(map);

            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("username", userInfo.getUsername());
            body.add("password", userInfo.getOpenId());
            body.add("grant_type", "password");
            body.add("scope", "all");
            Map<String, Object> stringObjectMap = null;
            try {
                stringObjectMap = feignAuthClient.generateToken(body);
            } catch (Exception e) {
                return CommonResult.failed(e.getMessage());
            }
            Object access_token = stringObjectMap.get("access_token");


            map.put("access_token", access_token);
            map.put("userId", userInfo.getId());
        }
        return CommonResult.success(map);
    }
    /**
     * @return  sessionKey 与 openId
     */
    @PostMapping(value = "/login_get_session")
    public CommonResult getSession(@RequestBody MiniLoginCodeRequest request, @RequestHeader String appId) {
        log.info("微信登录 port {}", serverPort);
        request.setAppId(appId);
        Map<String, Object> map = feignWxClient.miniLoginBySession(request);
        return CommonResult.success(map);
    }
    /**
     * @return 用户
     */
    @PostMapping(value = "/login_by_session")
    public CommonResult querySessionById(@RequestBody MiniLoginCodeRequest request, @RequestHeader String appId) {
        log.info("微信登录 port {}", serverPort);
        request.setAppId(appId);
        Map<String, Object> map = feignWxClient.miniLoginBySession(request);
        if (map.containsKey("code") && Integer.parseInt(map.get("code").toString()) == 200) {
            log.info("微信登录成功 port {}", map);
            UserInfo userInfo = null;
            try {
                userInfo = feignUserClient.queryByOpenId(map);
            } catch (Exception e) {
                return CommonResult.failed(e.getMessage());
            }
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("username", userInfo.getUsername());
            body.add("password", userInfo.getOpenId());
            body.add("grant_type", "password");
            body.add("scope", "all");
            Map<String, Object> stringObjectMap = null;
            try {
                stringObjectMap = feignAuthClient.generateToken(body);
            } catch (Exception e) {
                return CommonResult.failed(e.getMessage());
            }
            Object access_token = stringObjectMap.get("access_token");


            map.put("access_token", access_token);
            map.put("userId", userInfo.getId());
        }
        return CommonResult.success(map);
    }
    /**
     * @return 用户
     */
    @PostMapping(value = "/login_by_phone")
    public CommonResult queryPhoneById(@RequestBody MiniLoginRequest request, @RequestHeader String appId) {
        log.info("微信登录 port {}", serverPort);
        request.setAppId(appId);
        Map<String, Object> map = feignWxClient.miniLoginByPhone(request);
        if (map.containsKey("code") && Integer.parseInt(map.get("code").toString()) == 200) {
            log.info("微信登录成功 port {}", map);

            String openId = request.getOpenId();
            map.put("openId",openId);
            UserInfo userInfo = null;
            try {
                userInfo = feignUserClient.queryByOpenId(map);
            } catch (Exception e) {
                return CommonResult.failed(e.getMessage());
            }
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("username", userInfo.getUsername());
            body.add("password", userInfo.getOpenId());
            body.add("grant_type", "password");
            body.add("scope", "all");
            Map<String, Object> stringObjectMap = null;
            try {
                stringObjectMap = feignAuthClient.generateToken(body);
            } catch (Exception e) {
                return CommonResult.failed(e.getMessage());
            }
            Object access_token = stringObjectMap.get("access_token");


            map.put("access_token", access_token);
            map.put("userId", userInfo.getId());
        }
        return CommonResult.success(map);
    }

}
